package com.jboost.common.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.*;


@Slf4j
public class HttpRestUtils {

    /**
     * http json 提交 post
     */
    public static String post(String url, Map<String, Object> params,HttpHeaders headers) throws IOException {
        return httpClient(url, HttpMethod.POST, params,MediaType.APPLICATION_JSON_UTF8,headers);
    }

    /**
     * http 表单提交 post
     */
    public static String formPost(String url, Map<String, Object> params,HttpHeaders headers) throws IOException {
        return httpClient(url, HttpMethod.POST, params,MediaType.APPLICATION_FORM_URLENCODED,headers);
    }


    /**
     * http 表单提交 post
     */
    public static String formDataPost(String url, Map<String, Object> params,HttpHeaders headers) throws IOException {
        return httpClient(url, HttpMethod.POST, params,MediaType.MULTIPART_FORM_DATA,headers);
    }

    /**
     * http get
     */
    public static String get(String url, Map<String, Object> params,HttpHeaders headers) throws IOException {
        return httpClient(url, HttpMethod.GET, params,MediaType.APPLICATION_JSON_UTF8,headers);
    }

    /**
     * HttpMethod  post/get
     */
    public static String httpClient(String url, HttpMethod method, Map<String, Object> params,MediaType type,HttpHeaders headers) throws IOException {
        log.debug("-----post-----"+params.toString());
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(10 * 1000);
        requestFactory.setReadTimeout(10 * 1000);
        RestTemplate client = new RestTemplate(requestFactory);
        HttpEntity<Map<String, Object>> requestEntity = null;
        if(type == null || type == MediaType.APPLICATION_JSON_UTF8){
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
            requestEntity = new HttpEntity<Map<String, Object>>(params, headers);
        }else if (type == MediaType.APPLICATION_FORM_URLENCODED){
            headers.setContentType(type);
            MultiValueMap<String,Object> formParams = getMvMap(params);
            requestEntity = new HttpEntity(formParams, headers);
        }
        else if (type == MediaType.APPLICATION_JSON){
            headers.setContentType(type);
            MultiValueMap<String,Object> formParams = getMvMap(params);
            requestEntity = new HttpEntity(formParams, headers);
        }
        else if (type == MediaType.MULTIPART_FORM_DATA){
            headers.setContentType(type);
            MultiValueMap<String,Object> ret = new LinkedMultiValueMap<>();
            params.forEach((key,value)->{
                ret.put(key, new ArrayList(Arrays.asList(value)));
            });
            requestEntity = new HttpEntity(ret, headers);
        }
        //  执行HTTP请求
        ResponseEntity<String> response = null;
        System.out.println(JSONUtil.toJson(requestEntity));
        try {
            response = client.exchange(url, method, requestEntity, String.class);
            return response.getBody();
        } catch (HttpClientErrorException e) {
            System.out.println("------------- 出现异常 HttpClientErrorException -------------");
            System.out.println(e.getMessage());
            System.out.println(e.getStatusText());
            System.out.println("-------------responseBody-------------");
            System.out.println(e.getResponseBodyAsString());
            e.printStackTrace();
            return "";
        } catch (Exception e) {
            System.out.println("------------- HttpRestUtils.httpRestClient() 出现异常 Exception -------------");
            System.out.println(e.getMessage());
            return "";
        }
    }

    public static MultiValueMap<String,Object> getMvMap( Map<String, Object> map) {
        MultiValueMap<String,Object> ret = new LinkedMultiValueMap<String,Object>();
        map.forEach((key,value)->{
            ret.put(key, new ArrayList(Arrays.asList(value)));
        });
        return ret;
    }
}